package com.jjlin.chapter_8;

import java.util.*;
public class CD149{

    public static void spiralOrderPrint(int[][] matrix){
        if(matrix == null)
            return;
        int a = 0;
        int b = 0;
        int c = matrix.length - 1;
        int d = matrix[0].length - 1;
        while(a <= c && b <= d){
            printEdge(matrix, a++, b++, c--, d--);
        }
    }

    public static void printEdge(int[][] matrix, int a, int b, int c, int d){
        if(a == c){ //(a,b)和(c,d)同行
            for(int i = b; i <= d; i++)
                System.out.print(matrix[a][i] + " ");
        }else if(b == d){   //(a,b)和(c,d)同列
            for(int i = a; i <= c; i++)
                System.out.print(matrix[i][b] + " ");
        }else{
            int i = a;
            int j = b;
            while(j < d)
                System.out.print(matrix[i][j++] + " ");
            while(i < c)
                System.out.print(matrix[i++][j] + " ");
            while(j > b)
                System.out.print(matrix[i][j--] + " ");
            while(i > a)
                System.out.print(matrix[i--][j] + " ");
        }
    }

    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int row = sc.nextInt();
        int col = sc.nextInt();
        int[][] matrix = new int[row][col];
        for(int i = 0; i < row; i++)
            for(int j = 0; j < col; j++)
                matrix[i][j] = sc.nextInt();
        spiralOrderPrint(matrix);
    }
}